<!DOCTYPE html>
<html style="height: 100%;">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>TextPlayer</title>
    <script src="static/scripts/jquery.min.js"></script>
    <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/bootstrapQ/qiao.css" rel="stylesheet">
    <script type="text/javascript" src="static/bootstrapQ/qiao.js"></script>
    <link href="static/markdown/css/editormd.min.css" rel="stylesheet">
    <script type="text/javascript" src="js/common.js"></script>
    <script type="text/javascript" src="js/base64.js"></script>
    <script type="text/javascript" src="js/DocSys.js"></script>
    <script src="static/stackedit/docs/lib/stackedit.js"></script>
    
    <style type="text/css" media="screen">
	  body {
	      overflow: hidden;
	  }
	
	  #editor {
	      margin: 0 0 0 0;
	      position: absolute;
	      top: 0;
	      bottom: 0;
	      left: 0;
	      right: 0;
	  }
	</style>
    <!--编辑器的样式提取-->
	<style>
	.stackedit-no-overflow {
		overflow: hidden;
	}

	.stackedit-container {
		background-color: rgba(160, 160, 160, 0.5);
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 9999;
	}

	.stackedit-hidden-container {
		position: absolute;
		width: 10px;
		height: 10px;
		left: -99px;
	}

	.stackedit-iframe-container {
		background-color: #fff;
		position: absolute;
		margin: auto;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		height: 100%;
		width: 100%;
		border-radius: 2px;
		overflow: hidden;
	}

	.stackedit-iframe {
		position: absolute;
		height: 100%;
		width: 100%;
		border: 0;
		border-radius: 2px;
	}

	@media (max-width: 740px) {
		.stackedit-iframe-container {
			height: 100%;
			width: 100%;
			border-radius: 0;
		}

		.stackedit-iframe {
			border-radius: 0;
		}
	}

	.stackedit-close-button {
		position: absolute !important;
		box-sizing: border-box !important;
		width: 38px !important;
		height: 36px !important;
		margin: 4px !important;
		padding: 0 4px !important;
		text-align: center !important;
		vertical-align: middle !important;
		text-decoration: none !important;
	}
	</style>
</head>
<body style="height: 100%; margin: 0;">
    <div>
		<div id="textEditor">
			<!-- <div id="textEditorToolBar" style="height:40px;">
				<div class="editormd-toolbar" style="display: block;">
					<div class="editormd-toolbar-container">
						<ul id="toolBarMenu" class="editormd-menu" style="display:none;">
							<li><a href="javascript:;" onclick="saveDoc();" title="保存（Ctrl+S）" unselectable="on"><i class="fa fa-save" name="save" unselectable="on"></i></a></li>
						</ul>
						<ul id="switchEditMode" class="editormd-menu" style="position:absolute; right:5px;">
							<li id="textEditorCloseBtn" style="display:none;">
								<a href="javascript:;" onclick="exitEdit()" title="退出编辑" unselectable="on">
									<i class="fa fa-close" name="exitEdit" unselectable="on"></i>
								</a>
							</li>
							<li id="textEditorEditBtn">
								<a href="javascript:;" onclick="enableEdit()" title="编辑" unselectable="on">
									<i class="fa fa-edit" name="edit" unselectable="on"></i>
								</a>
							</li>
						</ul>				
					</div>
				</div>
			</div> -->
			<div class="textEditorContent" style="min-height: 600px;">
				<div id="editor">
					<div class="stackedit-container">
						<div class="stackedit-iframe-container">
							<iframe class="stackedit-iframe" src="#" width="100%" height="100%"></iframe>
						</div>
					</div>
				</div>
    		</div>
		</div>
    </div>  

	<script type="text/javascript">
	    var docInfo = getDocInfoFromRequestParamStr();
	    document.title = docInfo.name;
	    
	    if(!docInfo.fileSuffix)
	    {
	    	docInfo.fileSuffix = getFileSuffix(docInfo.name);
	    }
	    
		var docText = "";
		var tmpSavedDocText = "";
		var isContentChanged = false;
		var isReadOnly = false;
		var editState = false;
		
		//history file or file in zip is readonly
		checkAndSetIsReadOnly(docInfo);
		
		getDocText(docInfo, showText, showErrorMessage);
		
		function checkAndSetIsReadOnly(docInfo)
		{
			if(docInfo.isZip && docInfo.isZip == 1)
			{
				isReadOnly = true;
				return;
			}
			if(docInfo.isHistory && docInfo.isHistory == 1)
			{
				isReadOnly = true;
				return;
			}
		}
		
		/**
		 * 文档加载类
		 * @param docText_ 文档内容
		 * @param tmpSavedDocText_ 临时保存文档内容（暂时未使用）
		 */
		function showText(docText_, tmpSavedDocText_) {
			// 传入staticedit插件地址和文件内容，获取staticedit插件指定路径
			var url = getStaticEditUrl("/DocSystem/web/static/stackedit/dist/index.html",docText_);
			// 获取iframe并设置其src路径，渲染stackEdit编辑器，加载待修改markdown文件
			var stackEditIframeEl = $(".stackedit-iframe");
			stackEditIframeEl.prop("src",url);		

			// Listen to StackEdit events and apply the changes to the textarea.
			//监听iframe发来的消息
			window.addEventListener('message', messageHandler);
			// 设置定时0.5s后设置页面为只读
			setTimeout(function () {
				editState = false;
				setStaticEditReaOnly(false);
			},500)
		}

		/**
		 * staticEdit消息事件处理
		 * 
		 * @param event 事件对象
		 */
		function messageHandler(event) {
			switch (event.data.type) {
				case 'ready':
					// iframe 页面加载完成,设置当前页面为只读
					editState = false;
					setStaticEditReaOnly(false);
					break;
				case 'fileChange':
					if(isReadOnly == false)
					{
						//收到iframe文件改动消息
						var file = event.data.payload;
						docText = file.content.text;
						isContentChanged = true;
					}
					break;
				case 'close':
					//收到iframe的关闭消息
					var artDialog = top.dialog.get(window);
					artDialog.close();
					break;
				case 'saveChange':
					if(isContentChanged) {
						//执行文档保存操作
						saveDoc();	
					}
					break;
				case 'changeView':
					//当文档处于编辑状态要切换只读时触发
					if(event.data.flag) 
					{
						console.log("编辑器退出入编辑状态...");
						if(editState == true)
						{
							exitEdit();
						}
					}
					else
					{
						console.log("编辑器已进入编辑状态...");
						if(editState == false)
						{
							enableEdit();
						}
					}
					break;
				default:
			}
		}

		/**
		 * stackEdit插件加载路径初始化，在原始路径上拼装文件信息，域信息
		 *
		 * @param url 插件路径
		 * @param doc_text 文档内容
		 * @return 拼装后携带文件内容的url路径
		 */
		function getStaticEditUrl(url,doc_text) {
			var origin = window.location.protocol + '//' + window.location.host;
			var fileName = docInfo.name;
			var params = {
				origin: origin,
				fileName: fileName,
				contentText: doc_text,
				silent: false
			};
			var serializedParams = Object.keys(params).map(function (key) {
				return key + '=' + encodeURIComponent(params[key] || '');
			}).join('&');
			var hash = '#' + serializedParams;
			return url+hash;
		}

		/**
		 * 设置编辑器的编辑状态为只读
		 * 
		 * @param editFlag false代表编辑状态，true代表只读状态
		 */
		function setStaticEditReaOnly(editFlag) {
			var stackeditEl = $(".stackedit-iframe");
			if (stackeditEl !== undefined) {
				stackeditEl[0].contentWindow.postMessage({"type":"toggleEditor","flag":editFlag},"*")	
			}
		}

		/**
		 * 设置编辑器的保存按钮的开启和禁用
		 *
		 * @param editFlag false代表编辑状态，true代表只读状态
		 */
		function disabledEditState(editFlag) {
			var stackeditEl = $(".stackedit-iframe");
			if (stackeditEl !== undefined) {
				stackeditEl[0].contentWindow.postMessage({"type":"updateEditState","flag":editFlag},"*")
			}
		}

		
	    function saveDoc()
		{
	    	console.log("saveDoc docInfo.docId:" + docInfo.docId);
			
	    	if(isContentChanged == false)
	    	{
	    	   	console.log("saveDoc there is no change");
	    		return;
	    	}
	    	
			$.ajax({
	            url : "/DocSystem/Doc/updateDocContent.do",
	            type : "post",
	            dataType : "json",
	            data : {
	                reposId: docInfo.vid,
	            	docId : docInfo.docId,
	            	path: docInfo.path,
	                name: docInfo.name,
	            	content : docText,
	            	docType: 1, //RealDoc
	                shareId: docInfo.shareId,
	            },
	            success : function (ret) {
	                if( "ok" == ret.status ){
	                    console.log("保存成功 : " , (new Date()).toLocaleDateString());
	                    isContentChanged = false;	
	                    bootstrapQ.msg({
									msg : "保存成功 :" + (new Date()).toLocaleDateString(),
									type : 'success',
									time : 1000,
						});
					}else {
	                    bootstrapQ.alert("保存失败:"+ret.msgInfo);
	                }
	            },
	            error : function () {
	                bootstrapQ.alert("保存失败:服务器异常");
	            }
	        });
	    }
	
	    function enableEdit()
	    {
			console.log("enableEdit()");
			if(!docInfo.docId || docInfo.docId == 0)
			{
				editState = false;
				setStaticEditReaOnly(false);
				return;
			}

			$.ajax({
				url : "/DocSystem/Doc/lockDoc.do",
				type : "post",
				dataType : "json",
				data : {
					lockType : 1, //LockType: Online Edit
					reposId : docInfo.vid, 
					docId : docInfo.docId,
					path: docInfo.path,
					name: docInfo.name,
					docType: 1,
	                shareId: docInfo.shareId,
				},
				success : function (ret) {
					if( "ok" == ret.status)
					{
						console.log("enableEdit() ret.data",ret.data);
						$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","red");

						editState = true; //编辑器已处于编辑状态不需要切换
						return;
	 				}
					else
					{
						//锁定失败，切换编辑状态，但要避免触发exitEdit
						editState = false;
						setStaticEditReaOnly(false);				
						return;
					}
				},
				error : function () 
				{
					editState = false;
					setStaticEditReaOnly(false);				
					return;
				}
			});
	    }
	    
		//退出文件编辑状态
	    function exitEdit() {   	
			console.log("exitEdit()  docInfo.docId:" + docInfo.docId);
			if(!docInfo.docId || docInfo.docId == 0)
			{
				editState = false;
				setStaticEditReaOnly(false);
				return;
			}
			
			$.ajax({
				url : "/DocSystem/Doc/unlockDoc.do",
				type : "post",
				dataType : "json",
				data : {
					lockType : 1, //unlock the doc
					reposId : docInfo.vid, 
	            	docId : docInfo.docId,
					path: docInfo.path,
					name: docInfo.name,
					docType: 1,
	                shareId: docInfo.shareId,
				},
				success : function (ret) {
					if( "ok" == ret.status)
					{
						console.log("exitEdit() ret:",ret.data);
						$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","black");
						editState = false;
						return;
	 				}
					else
					{
						editState = true;
						setStaticEditReaOnly(true);
						return;
					}
				},
				error : function () 
				{
					editState = true;
					setStaticEditReaOnly(true);
					return;
				}
			});
		}
    </script>
</body>
</html>